﻿using Abp.Events.Bus;
using AbpProjectTemplate.Components.Payments.Event;
using Castle.Core.Logging;
using Castle.DynamicProxy;
using Newtonsoft.Json;
using System.Reflection;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Components.Payments
{
    public class PaymentApiInterceptor : StandardInterceptor
    {
        private readonly IEventBus _eventBus;
        public ILogger Logger { get; set; }
        public PaymentApiInterceptor(IEventBus eventBus)
        {
            this._eventBus = eventBus;
            this.Logger = NullLogger.Instance;
        }

        protected override void PostProceed(IInvocation invocation)
        {
            //拦截支付通知以触发事件
            if (invocation.Method.Name.Contains("Notify"))
            {
                var task = invocation.ReturnValue as Task;
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    var data = task.GetType().GetTypeInfo()
                        .GetProperty("Result")
                        ?.GetValue(task, null);
                    this.Logger.Debug($"执行支付通知事件：{JsonConvert.SerializeObject(data)}");
                    this._eventBus.Trigger((PaymentNotifyEventData)data);
                }
            }
        }
    }
}
